/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "iap.h"
/* Private includes ----------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include "ymodem.h"
/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/
#define SOFT_VERSION    "1.0.1"
#define RX_BUFFER_LEN   1280
/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_rx;

typedef struct 
{
  uint8_t buf[RX_BUFFER_LEN];
	uint16_t len;
  uint16_t index;
}RxBufferTypeDef;

RxBufferTypeDef rxBuffer;
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_DMA_Init(void);
/* Private user code ---------------------------------------------------------*/

uint8_t buffer[2048];
uint8_t sendFlag;
uint16_t sendLen;
/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* MCU Configuration--------------------------------------------------------*/
  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  
  bootloader_display();
  /* enter iap process */
  if(get_iap_signal(5000) == 0)
  {
    printf("\r\nenter iap process\r\n");
    printf("please transmit binary file(press 'a' or 'A' to cancel)\r\n");
    ymodem_receive(buffer);
    HAL_Delay(100);
    printf("download new firmware successed\r\n");
    printf("turn to app\r\n");
    turn_to_app();
  }
  /* turn to app */
  else
  {
    printf("\r\nturn to app\r\n");
    turn_to_app();
  }
  
  while(1)
  {
    printf("hello bootloader\r\n");
    HAL_Delay(1000);
  }
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
  HAL_UART_Receive_DMA(&huart1, rxBuffer.buf, RX_BUFFER_LEN);
}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
}

int _write(int fd, char *ptr, int len)  
{  
  HAL_UART_Transmit(&huart1, (uint8_t*)ptr, len, 0xFFFF);
  return len;
}

/* 0 for received; -1 for no data */
int8_t uart_getchar(uint8_t *data, uint32_t timeout)
{
  while(timeout)
  {
    if(rxBuffer.len)
    {
      *data = rxBuffer.buf[0];
      rxBuffer.index += 1; 
      rxBuffer.len -= 1;
      return 0;
    }
    else
    {
      rxBuffer.index = 0; 
    }
    HAL_Delay(100);
    timeout -= 100;
  }
  return -1;
}

int8_t uart_getstream(uint8_t *data, uint32_t len, uint32_t timeout)
{
  uint32_t dataLen = 0;
  int8_t ret = 0;
  while(timeout)
  {
    if(rxBuffer.len)
    {
      dataLen += rxBuffer.len;
      if(dataLen <= len)
      {
        memcpy((char *)data, (char *)&rxBuffer.buf[rxBuffer.index], rxBuffer.len);
        data += rxBuffer.len;
      }
      else
      {
        ret = -1;
        return ret;
      }
      rxBuffer.len = 0;
      rxBuffer.index = 0;
    }
    else
    {
      rxBuffer.index = 0;
    }
    if(dataLen < len)
    {
      HAL_Delay(100);
      timeout -= 100;
    }
    else
    {
      ret = 0;
      return ret;
    }
  }
  return -1;
}

void uart_putchar(uint8_t data)
{
  HAL_UART_Transmit(&huart1, (uint8_t*)&data, 1, 0xFFFF);
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
}
#endif /* USE_FULL_ASSERT */

void USART1_IRQHandler(void)
{
  if(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)  // 空闲中断标记被置位
  {
    __HAL_UART_CLEAR_IDLEFLAG(&huart1);  // 清楚中断标记
    HAL_UART_DMAStop(&huart1);           // 停止DMA接收
    rxBuffer.len = RX_BUFFER_LEN - __HAL_DMA_GET_COUNTER(huart1.hdmarx);
    HAL_UART_Receive_DMA(&huart1, rxBuffer.buf, RX_BUFFER_LEN);
  }
}
